package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 代码清单 ch02-04：AsynchronousFileChannel将来式示例(2.5.1节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/13 18:10
 */
public class AsynchronousFileChannel1Demo {

    private static final Logger logger = LogManager.getLogger(AsynchronousFileChannel1Demo.class);

    public static void main(String[] args) {
        logger.info("...代码清单 ch02-04：AsynchronousFileChannel将来式示例(2.5.1节)...");

        try {

            Path file = Paths.get("D:\\works\\workspace\\readme.txt");

            // 异步打开文件
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);

            // 读取 100 000 字节
            ByteBuffer buffer = ByteBuffer.allocate(100_000);
            Future<Integer> result = channel.read(buffer, 0);

            while (!result.isDone()) {
                // 干点儿别的事情
                ProfitCalculator.calculateTax();
            }

            // 获取结果
            Integer bytesRead = result.get();
            System.out.println("Bytes read [" + bytesRead + "]");

        } catch (IOException | ExecutionException | InterruptedException e) {
            System.out.println(e.getMessage());
        }


    }


    private static class ProfitCalculator {

        public ProfitCalculator() {}

        public static void calculateTax() {}
    }

}
